package com.cxs.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * @Author:cxs
 * @Date:2021/10/15  8:50
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@WebFilter(urlPatterns = "/*")
public class CorsFilterConfig implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(CorsFilterConfig.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PATCH,DELETE,PUT,OPTIONS");
        /*
         * 该字段可选，用来指定本次预检请求的有效期，单位为秒。上面结果中，有效期是1小时（3600秒），
         * 即允许缓存该条回应3600秒（即1小时），在此期间，不用发出另一条预检请求。
         */
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        response.setHeader("Content-Type","application/json;charset=UTF-8");
        // prefight请求
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus( 200 );
            return;
        }
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}
